import React, { memo, useMemo, useState, useEffect, useCallback, useContext } from 'react';
import { Icon, Typography, Tooltip, Form, Modal, Col, Checkbox, Select } from 'antd';
import classNames from 'classnames';
import { history } from 'umi'

import Pagination from '@/components/Pagination';
import If from '@/components/If';

import { NumberSettingInput } from '@/pages/SalaryManage/components/NumberSettingInput';
import TablePercentWrapper from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/TablePercentWrapper';
import SummaryTable from '@/components/SummaryTable';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import { queryDictList } from '@/services/salaryManage/salaryCalculate';

import SalaryPageProvider from '@/pages/SalaryManage/components/SalaryPageWrapper/SalaryPageProvider';
import styles from './index.less';

/**
 * @param rowKey
 * @param tableHeader
 * @param { ColumnProcessor } columnProcessor
 * @param dataSource
 * @param pagination
 * @param dispatch
 * @param dispatchType
 * @param hideSelection
 * @returns {*}
 * @constructor
 */
const CheckBody = ({
    rowKey,
    tableHeader,
    columnProcessor,
    summaryFields = [],
    dataSource,
    pagination,
    changePage,
    tableLoading,
    hideSecurityTip = false,
    hideSelection,
    jumpItem = true,
    selectedRows = [],
    tableProps = {}
}) => {
    const salaryProvider = useContext(SalaryPageProvider);
    const { organizationCode, searchModel, changeSalaryProviderParam } = salaryProvider;
    const [visible, SetVisible] = useState(false);
    const [rateEnumList, setRateEnumList] = useState({});
    const getDictList = async () => {
        try {
            const { code, data = {} } = await queryDictList('salaryPayrollRateEnum,socialTypeWebFlagEnum');
            if (code === 10000) {
                setRateEnumList(data || {});
            }
        } catch (e) {
            console.log(e);
        }
    };

    // 获取字典
    useEffect(() => {
        getDictList();
    }, []);

    // 切换分页
    const tablePageChange = ({ current, pageSize }) => {
        changePage({
            pagination: { current, pageSize }
        });
    };

    //  弹窗确定按钮事件
    const okHandle = useCallback(
        (value = {}) => {
            SetVisible(false);
            const { contrastType, downAbnormalTipIndex, upAbnormalTipIndex, salaryRateKpiInd } = value;
            changeSalaryProviderParam({
                searchModel: {
                    ...searchModel,
                    contrastType,
                    downAbnormalTipIndex,
                    upAbnormalTipIndex,
                    salaryRateKpiInd: salaryRateKpiInd && salaryRateKpiInd.length > 0 ? salaryRateKpiInd[0] : 0
                }
            });
        },
        [changeSalaryProviderParam, searchModel]
    );

    // 比例设置弹窗
    const ContrastModal = useMemo(
        () =>
            Form.create({})(({ form }) => {
                const { getFieldDecorator, getFieldsValue, validateFields } = form;
                const {
                    contrastType = 1,
                    downAbnormalTipIndex,
                    upAbnormalTipIndex,
                    salaryRateKpiInd = 1
                } = searchModel;

                const contrastOkHandle = () => {
                    validateFields(errors => {
                        if (!errors) {
                            okHandle(getFieldsValue());
                        }
                    });
                };

                return (
                    <Modal
                        visible={visible}
                        title="设置对比"
                        okText="确定"
                        cancelText="取消"
                        centered
                        onOk={contrastOkHandle}
                        onCancel={() => SetVisible(false)}
                    >
                        <Form
                            layout="horizontal"
                            style={{ marginTop: 20 }}
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}
                        >
                            <Form.Item label="展示">
                                <Col span={14}>
                                    <Form.Item style={{ marginBottom: 0 }}>
                                        {getFieldDecorator('contrastType', {
                                            initialValue: contrastType
                                        })(
                                            <Select>
                                                {rateEnumList?.salaryPayrollRateEnum?.map(item => (
                                                    <Select.Option value={item.key} key={item.key}>
                                                        {item.value}
                                                    </Select.Option>
                                                ))}
                                            </Select>
                                        )}
                                    </Form.Item>
                                </Col>
                                <Col span={10}>
                                    <Form.Item style={{ marginBottom: 0 }}>
                                        {getFieldDecorator('salaryRateKpiInd', {
                                            initialValue: [salaryRateKpiInd]
                                        })(
                                            <Checkbox.Group style={{ marginLeft: 15 }}>
                                                <Checkbox value={1}>含绩效薪资</Checkbox>
                                            </Checkbox.Group>
                                        )}
                                    </Form.Item>
                                </Col>
                            </Form.Item>
                            <Form.Item label="下降">
                                超过
                                <span style={{ display: 'inline-block', width: 100, marginLeft: 5 }}>
                                    {getFieldDecorator('downAbnormalTipIndex', {
                                        initialValue: downAbnormalTipIndex,
                                        rules: [
                                            {
                                                type: 'number',
                                                max: 100,
                                                message: '不能超过100%'
                                            }
                                        ]
                                    })(<NumberSettingInput thousandsSeparator="," />)}
                                </span>{' '}
                                % 时异常展示
                            </Form.Item>
                            <Form.Item label="上升">
                                超过
                                <span style={{ display: 'inline-block', width: 100, marginLeft: 5 }}>
                                    {getFieldDecorator('upAbnormalTipIndex', {
                                        initialValue: upAbnormalTipIndex,
                                        rules: [
                                            {
                                                type: 'number',
                                                max: 100,
                                                message: '不能超过100%'
                                            }
                                        ]
                                    })(<NumberSettingInput thousandsSeparator="," />)}
                                </span>{' '}
                                % 时异常展示
                            </Form.Item>
                        </Form>
                    </Modal>
                );
            }),
        [okHandle, rateEnumList, searchModel, visible]
    );

    //  百分比设置
    const ScaleWrapper = ({ title }) => (
        <>
            <EmptyPlaceHolder value={title} />
            <i
                className={classNames('icon', 'iconfont', 'iconshezhi', styles.scale)}
                onClick={() => SetVisible(true)}
            />
        </>
    );

    // const payrollSocial = [
    //     'encryptOldPersonAmt', // 养老
    //     'encryptUnemployPersonAmt', // 失业
    //     'encryptHospitalPersonAmt', // 医疗
    //     'encryptFundPersonAmt', // 公积金
    //     'encryptBirthPersonAmt', // 生育
    //     'encryptHarmPersonAmt', // 工伤
    //     'encryptIllPersonAmt', // 大病
    //     'encryptPersonTotalAmt' // 合计
    // ];

    const payrollSocial = useMemo(() => rateEnumList.socialTypeWebFlagEnum?.map(item => item.key) || [], [
        rateEnumList
    ]);

    //  表单点击处理
    const tableItemClick = useCallback(
        (header, record) => {
            if (header.enableClickJump === 1 && jumpItem && !record.$$isSummary) {
                const year = record.yearMonth?.substr(0, 4) || '';
                const month = record.yearMonth?.substr(5) || '';

                history.push({
                    pathname: '/finance/salary/calculate/recheck/itemrecheck',
                    state: {
                        tabRoute: true,
                        tabRefresh: true
                    },
                    query: {
                        parentId: header.leafSalaryItemId,
                        organizationCode,
                        employeeCode: record.employeeCode,
                        period: `${year}-${month < 10 ? '0' : ''}${month}`,
                        leafSalaryItemId: payrollSocial.includes(header.key) ? '' : header.key
                    }
                });
            }
        },
        [jumpItem, organizationCode]
    );

    //  重新组装头部
    const renderColumns = useMemo(
        () =>
            columnProcessor
                .merge(tableHeader, tableItemClick)
                .filter(item => !item.hidden)
                .map(item => {
                    if (item.scale) {
                        const { title } = item;
                        return {
                            ...item,
                            title: <ScaleWrapper title={title} />,
                            render: (text, record) =>
                                record.$$isSummary || record.rateUpOrDown === 0 ? (
                                    <EmptyPlaceHolder />
                                ) : (
                                    <TablePercentWrapper
                                        rate={text}
                                        type={
                                            {
                                                0: '',
                                                1: 'up',
                                                2: 'down'
                                            }[record.rateUpOrDown]
                                        }
                                    />
                                )
                        };
                    }
                    return item;
                }),
        [columnProcessor, tableHeader, tableItemClick]
    );

    const vvSummaryFields = useMemo(() => {
        if (!summaryFields) {
            return [];
        }

        if (Array.isArray(summaryFields)) {
            return summaryFields;
        }

        return summaryFields(tableHeader);
    }, [summaryFields, tableHeader]);

    const dynamicProps = hideSelection
        ? {}
        : {
              rowSelection: {
                  type: 'checkbox',
                  fixed: true,
                  columnWidth: 50,
                  selectedRowKeys: selectedRows.map(item => item.id),
                  onChange(selectedRowKeys, selectedRowsNew) {
                      changeSalaryProviderParam({
                          selectedRows: selectedRowsNew
                      });
                  },
                  getCheckboxProps: record => ({
                      disabled:
                          record?.buttons?.filter(item => item.code === 9 || item.code === 15)[0]?.disabled === true
                  })
              }
          };

    return (
        <div className={styles.CheckBody}>
            <div>
                <SummaryTable
                    {...dynamicProps}
                    bordered
                    columns={renderColumns}
                    vvSummaryFields={vvSummaryFields}
                    rowKey={rowKey}
                    dataSource={dataSource}
                    pagination={false}
                    loading={tableLoading}
                    scroll={{ x: 'max-content' }}
                    {...tableProps}
                />
            </div>
            {hideSecurityTip ? null : (
                <div className={styles.securityTip}>
                    <Tooltip
                        overlay={
                            <ul>
                                <li>薪资细项所有的薪酬数据均采用非对称加密算法，即便数据库管理员也无法查看原始数据</li>
                                <li>薪酬管理员只可查看和管理自己发放的薪资条</li>
                            </ul>
                        }
                        placement="topLeft"
                        overlayClassName={styles.dropdownOverlay}
                    >
                        <span style={{ cursor: 'pointer' }}>
                            <Typography.Text type="secondary" style={{ marginRight: 5 }}>
                                数据隐私
                            </Typography.Text>
                            <Icon type="question-circle" />
                        </span>
                    </Tooltip>
                </div>
            )}

            <Pagination {...pagination} onChange={tablePageChange} />
            <If condition={visible}>
                <ContrastModal />
            </If>
        </div>
    );
};

export default memo(CheckBody);
